package cn.liuyang.tinyioc.aop;

import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态生成代理对象
 * Created by liuyang on 2018/4/10.
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

    private AdvisedSupport advised;

    public JdkDynamicAopProxy(AdvisedSupport advised) {
        this.advised = advised;
    }

    /**
     * 生成代理对象,代理对象会将JdkDynamicAopProxy通过构造方法初始化，名字为Proxy类中的h
     *
     * @return
     */
    @Override
    public Object getProxy() {
        Object object = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{advised.getTargetSource()
                .getTargetClass()}, this);
        return object;
    }

    /**
     * 方法拦截器对方法进行拦截和织入
     * 方法调用时，实际执行的是代理类中的这个方法：super.h.invoke(this, m3, (Object[])null)
     *
     * @param proxy  动态生成的代理对象
     * @param method 被代理的方法
     * @param args   参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodInterceptor methodInterceptor = advised.getMethodInterceptor();
        // 第一个对象一开始传成 proxy 了，导致循环调用，报stackoverflow异常
        return methodInterceptor.invoke(new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(), method, args));
    }

}
